//
//  MYOAuthViewController.m
//  奇闻
//
//  Created by 似水灵修 on 14-11-24.
//  Copyright (c) 2014年 MingYueGuCheng. All rights reserved.
//

#import "MYOAuthViewController.h"
#import "MBProgressHUD+MJ.h"
#import "MYAccountTool.h"
#import "MYChooseContrllerTool.h"

@interface MYOAuthViewController ()<UIWebViewDelegate>

@end
@implementation MYOAuthViewController
- (void)loadView
{
    self.view = [[UIWebView alloc] initWithFrame:MYScreenBounds];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIWebView *webView = (UIWebView *)self.view;
    webView.delegate = self;
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@", MYAppKey, MYRedirectURI];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    [webView loadRequest:request];
}
//开始请求
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [MBProgressHUD showMessage:@"正在加载。。。"];
}
//请求失败
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [MBProgressHUD showError:[NSString stringWithFormat:@"%@", error]];
}
//请求完成
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [MBProgressHUD hideHUD];
}
//每当webView加载页面时调用，加载一个请求时讯问是否允许加载
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    [MBProgressHUD hideHUD];
    //获取请求加载的URL
    //通过未授权的request token获取授权的request token
    NSString *urlStr = request.URL.absoluteString;
    NSString *str = [NSString stringWithFormat:@"%@/?code=", MYRedirectURI];
    NSRange range = [urlStr rangeOfString:str];
    if (NSNotFound != range.location) {
        NSString *code = [urlStr substringFromIndex:range.location + range.length];
        [self accessTokenWithCode:code];
        return NO;
    }
    return YES;
}
//通过授权的request token获取access token
- (void)accessTokenWithCode:(NSString *)code
{
    [MYAccountTool accessTokenWithCode:code success:^() {
        [MBProgressHUD hideHUD];
        // 选择进入新特性还是首页
        // 判断有没有新特性,从而选择窗口的根控制器
        [MYChooseContrllerTool chooseRootViewController:MYKeyWindow];
    } failure:^(NSError *error) {
//        MYLog(@"请求失败：%@", error);
    }];
}
@end
